from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

data = load_iris()
x = data.data
y = data.target

x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=123)

import pandas as pd
import numpy as np
df = pd.DataFrame(np.c_[x_test, y_test])
df.to_csv('1.csv')

from tensorflow.keras import layers, models, optimizers, losses, metrics
from tensorflow.keras import utils

#将y数据进行独热编码，因为loss用的是CategoricalCrossentropy()多分类交叉熵
y_train = utils.to_categorical(y_train, 3)
y_test = utils.to_categorical(y_test, 3)

#构建模型序列
model = models.Sequential()
model.add(layers.Dense(3, input_dim=(4), activation='softmax'))

model.compile(optimizer=optimizers.Adam(0.01),
              loss=losses.CategoricalCrossentropy(), metrics=['accuracy'])  #CategoricalCrossentropy()使用独热

history = model.fit(x_train, y_train, epochs=100, validation_data=(x_test, y_test))

#存储模型: 模型结构和参数
model.save('1.h5')

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']

loss = history.history['loss']
accuracy = history.history['accuracy']
val_loss = history.history['val_loss']
val_accuracy = history.history['val_accuracy']

plt.plot(loss, color='red', label='训练损失')
plt.plot(val_loss, color='blue', label='测试损失')
plt.legend()
plt.show()

